﻿using Kinlo.Entitys;
using MaterialDesignThemes.Wpf;
using NewLife.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using UIWindows.Commands;
using UIWindows.Domains;
using UIWindows.Enums;
using UIWindows.GlobalStatics;
using UIWindows.Models;
using UIWindows.Services;
using UIWindows.Tools.Helper;
using UIWindows.UserControls;
using UIWindows.Views.Dialogs;
using XCode;
using XingLucifer.IBase.Enums;

namespace UIWindows.ViewModels
{
    public class ProductionHistoryViewModel : Domains.ViewModelBase, XingLucifer.IBase.IViewStatus
    {

        #region 分页
        private int _displayDataCount;
        /// <summary>
        /// 当前显示的数量
        /// </summary>
        public int DisplayDataCount
        {
            get { return _displayDataCount; }
            set { SetProperty(ref _displayDataCount, value); }
        }

        private int _quiryTotal;
        /// <summary>
        /// 查询出来的数据
        /// </summary>
        public int QuiryTotal
        {
            get { return _quiryTotal; }
            set { SetProperty(ref _quiryTotal, value); }
        }

        /// <summary>
        /// 当前显示的页数
        /// </summary>
        private int _severalPage;

        public int SeveralPage
        {
            get { return _severalPage; }
            set { SetProperty(ref _severalPage, value); }
        }


        private int _totalPage;
        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPage
        {
            get { return _totalPage; }
            set { SetProperty(ref _totalPage, value); }
        }


        private int _pageCount;
        /// <summary>
        /// 每页数量
        /// </summary>
        public int PageCount
        {
            get { return _pageCount; }
            set { SetProperty(ref _pageCount, value); }
        }

        /// <summary>
        /// 每页数量下拉选择
        /// </summary>
        public List<int> PageCountList { get; set; } = new List<int>();
        #endregion

        #region 条件
        private bool _isOutput;
        /// <summary>
        /// 是否出站
        /// </summary>
        public bool IsOutput
        {
            get { return _isOutput; }
            set { SetProperty(ref _isOutput, value); }
        }

        public DateTime StartTime { get; set; }
        public string StartValidatingTime { get; set; }
        public DateTime EndTime { get; set; }
        public string EndValidatingTime { get; set; }
        /// <summary>
        /// 条码
        /// </summary>
        public string Barcode { get; set; }
        /// <summary>
        /// 间隔时间
        /// </summary>
        public int Intervals { get; set; } = 100;
        #endregion

        #region 配置显示项
        public GridView ProductionDataView { get; set; }
        #endregion

        #region 单例
        public DisplayItemsStatic _displayItems;
        #endregion

        #region 删选

     
        
        private string _resultTotalValue = "全部";
        /// <summary>
        /// 总结果
        /// </summary>
        public string ResultTotalValue
        {
            get { return _resultTotalValue; }
            set { SetProperty(ref _resultTotalValue, value); }
        }

        private string _resultScanCodeBeforeValue = "全部";
        /// <summary>
        /// 前扫码结果
        /// </summary>
        public string ResultScanCodeBeforeValue
        {
            get { return _resultScanCodeBeforeValue; }
            set { SetProperty(ref _resultScanCodeBeforeValue, value); }
        }

        private string _resultShortCicuteValue = "全部";
        /// <summary>
        /// 短路测试仪结果
        /// </summary>
        public string ResultShortCicuteValue
        {
            get { return _resultShortCicuteValue; }
            set { SetProperty(ref _resultShortCicuteValue, value); }
        }
        private string _resultFormerWeighing = "全部";
        /// <summary>
        /// 前称重结果
        /// </summary>
        public string ResultFormerWeighingValue
        {
            get { return _resultFormerWeighing; }
            set { SetProperty(ref _resultFormerWeighing, value); }
        }

        private string _resultAfterWeighingValue = "全部";
        /// <summary>
        /// 后称重结果
        /// </summary>
        public string ResultAfterWeighingValue
        {
            get { return _resultAfterWeighingValue; }
            set { SetProperty(ref _resultAfterWeighingValue, value); }
        }

        private string _resultRefillWeighingValue = "全部";
        /// <summary>
        /// 补称重结果
        /// </summary>
        public string ResultRefillWeighingValue
        {
            get { return _resultRefillWeighingValue; }
            set { SetProperty(ref _resultRefillWeighingValue, value); }
        }

        private string _leakResultValue = "全部";
        /// <summary>
        /// 测漏结果
        /// </summary>
        public string LeakResultValue
        {
            get { return _leakResultValue; }
            set { SetProperty(ref _leakResultValue, value); }
        }

        private string _afterSealingResultValue = "全部";
        /// <summary>
        /// 密封钉结果
        /// </summary>
        public string AfterSealingResultValue
        {
            get { return _afterSealingResultValue; }
            set { SetProperty(ref _afterSealingResultValue, value); }
        }

        public List<object> MachineInfoList { get; set; } = new List<object>();

        /// <summary>
        /// 总结果下拉选择
        /// </summary>
        public List<object> ResultTotaList { get; set; } = new List<object>();
     
        /// <summary>
        /// 前扫码结果下拉选择
        /// </summary>
        public List<object> ResultScanCodeBeforeList { get; set; } = new List<object>();
        /// <summary>
        /// 短路测试仪结果下拉选择
        /// </summary>
        public List<object> ResultShortCicuteList { get; set; } = new List<object>();
        /// <summary>
        /// 前称重结果下拉选择
        /// </summary>
        public List<object> ResultFormerWeighingList { get; set; } = new List<object>();
        /// <summary>
        /// 后称重结果下拉选择
        /// </summary>
        public List<object> ResultAfterWeighingList { get; set; } = new List<object>();
        /// <summary>
        /// 补液称重结果下拉选择
        /// </summary>
        public List<object> ResultRefillWeighingList { get; set; } = new List<object>();
        /// <summary>
        /// 测漏结果下拉选择
        /// </summary>
        public List<object> LeakResultList { get; set; } = new List<object>();

        /// <summary>
        /// 密封钉结果下拉选择
        /// </summary>
        public List<object> AfterSealingResultList { get; set; } = new List<object>();



        #endregion



        private bool _isBarcodeDisplay;


        /// <summary>
        /// 是否显示托盘码输入框
        /// </summary>
        public bool IsBarcodeDisplay
        {
            get { return _isBarcodeDisplay; }
            set
            {
                if (_isBarcodeDisplay != value)
                {
                    _isBarcodeDisplay = value;  // 更新属性的值
                    OnPropertyChanged(nameof(IsBarcodeDisplay));  // 通知属性已更改
                }
            }
        }
        

        private MachineInfoTypes _machineInfoValue= MachineInfoTypes.折极耳;
        /// <summary>
        /// 选择要查询的设备
        /// </summary>
        public MachineInfoTypes MachineInfoValue
        {
            get { return _machineInfoValue; }
            set
            {

                if (_machineInfoValue != value)
                {
                    ViewUpdate(value);
                    SetProperty(ref _machineInfoValue, value);
                }
            }
        }
        public AsyncObservableCollection<object> WeightList { get; set; }
        
        public SystemConfigStatic _configStatic { get; set; }
        public ProductionHistoryViewModel(DisplayItemsStatic displayItems, SystemConfigStatic systemConfigStatic)
        {

            IsBarcodeDisplay = false;
            _configStatic =systemConfigStatic;
        
            _displayItems = displayItems;

            PageCountList.AddRange(new List<int>
            {
                10,
                50,
                100,
                120,
                200,
                500,
                1000
            });


            WeightList = new AsyncObservableCollection<object>();
            StartTime = DateTime.Now.Date;
            //StartTime = "2023/07/1".ToDateTime();
            StartValidatingTime = "00:00:00";
            //EndTime = "2023/07/5".ToDateTime();
            EndTime = DateTime.Now.Date;
            EndValidatingTime = "23:59:59";
            SeveralPage = 1;
            DisplayDataCount = 0;
            TotalPage = 1;
            PageCount = 50;
            QuiryTotal = 0;
            ProductionDataView = new GridView();
         

        }

        private bool TimeInterval(DateTime dateTime) => ((DateTime.Now.Day - dateTime.Day) == 1) && (DateTime.Now.Hour == 1);

        /// <summary>
        /// 上一页
        /// </summary>
        public DelegateCommand PreviousPage => new DelegateCommand(() =>
        {
            if (SeveralPage - 1 > 0)
            {
                WeightList.Clear();
                SeveralPage -= 1;
                Quiry();
            }
        });

        /// <summary>
        /// 下一页
        /// </summary>
        public DelegateCommand NextPage => new DelegateCommand(() =>
        {
            if ((SeveralPage + 1) <= TotalPage)
            {
                WeightList.Clear();
                SeveralPage += 1;
                Quiry();
            }
        });

        /// <summary>
        /// 数据查询
        /// </summary>
        public DelegateCommand QueryData => new DelegateCommand(() =>
        {
            if (StartTime.Year != EndTime.Year)
            {
                "请选择相同年份".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                return;
            }
            if (StartTime.GetQuarterly() != EndTime.GetQuarterly())
            {
                $"请选择季度内查询\r\n1月至3月为一个季度\r\n4月至6月为一个季度\r\n7月至9月为一个季度\r\n10月至12月为一个季度\r\n".MessageDialogs(MessageLevelType.警告, false, PopUpTypes.Global);
                return;
            }
            SeveralPage = 1;
            DisplayDataCount = 0;
            TotalPage = 1;
            QuiryTotal = 0;
            WeightList.Clear();
            _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);
            Quiry();
        });

        /// <summary>
        /// 导出数据
        /// </summary>
        //public DelegateCommand ExportData => new DelegateCommand(() =>
        //{
        //    Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
        //    openFileDialog.Title = "选择文件";
        //    openFileDialog.Filter = "所有文件(*.*)|*.*";
        //    openFileDialog.FileName = "选择文件夹";
        //    openFileDialog.FilterIndex = 1;
        //    openFileDialog.ValidateNames = false;
        //    openFileDialog.CheckFileExists = false;
        //    openFileDialog.CheckPathExists = true;
        //    openFileDialog.Multiselect = false;//允许同时选择多个文件
        //    if (openFileDialog.ShowDialog() == true)
        //    {
        //        string path = openFileDialog.FileName.Replace("选择文件夹", null, StringComparison.Ordinal);
        //        _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);
        //        Task.Run(() =>
        //        {
        //            ProductionData.Meta.TableName = $"ProductionData_{StartTime:yyyy}{StartTime.GetQuarterly()}";
        //            string[] stime = StartValidatingTime.Split(':');
        //            string[] etime = EndValidatingTime.Split(':');
        //            long startTime = SnowflakeManager.GetTimeId(new DateTime(StartTime.Year, StartTime.Month, StartTime.Day, int.Parse(stime[0]), int.Parse(stime[1]), int.Parse(stime[2]), 0, DateTimeKind.Local));
        //            long endTime = SnowflakeManager.GetTimeId(new DateTime(EndTime.Year, EndTime.Month, EndTime.Day, int.Parse(etime[0]), int.Parse(etime[1]), int.Parse(etime[2]), 999, DateTimeKind.Local));
        //            XCode.Expression expression = ProductionData._.SnowflakeId >= startTime & ProductionData._.SnowflakeId <= endTime;
        //            if (!string.IsNullOrEmpty(Barcode))
        //            {
        //                var str_barcode = Barcode.Split("\r\n");
        //                XCode.Expression barcode_expression = ProductionData._.BarCode.Contains(str_barcode[0]);
        //                for (int i = 1; i < str_barcode.Length; i++)
        //                {
        //                    if (!string.IsNullOrEmpty(str_barcode[i]))
        //                    {
        //                        barcode_expression |= ProductionData._.BarCode.Contains(str_barcode[i]);
        //                    }
        //                }
        //                expression &= (barcode_expression);
        //            }
        //            if (ExportHelper.Export_ProductionData($"{path}注液数据{DateTime.Now:yyyy_MM_dd_HH_mm_ss}.xls", expression, _displayItems.WeighingDisplayItems))
        //            {
        //                "导出完成".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);
        //            }
        //            else
        //            {
        //                "导出失败".MessageDialogs(MessageLevelType.错误, false, PopUpTypes.Global);
        //            }
        //        });
        //    }
        //});


        public DelegateCommand ExportData => new DelegateCommand(() =>
        {
            Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog.Title = "选择保存路径";
            //saveFileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx|Excel文件(*.xls)|*.xls|CSV文件(*.csv)|*.csv";
            saveFileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";
            //saveFileDialog.Filter = "CSV文件(*.csv)|*.csv|Excel文件(*.xls)|*.xls"; 
            saveFileDialog.FilterIndex = 1;

            // Set default file name
            saveFileDialog.FileName = $"{MachineInfoValue}{DateTime.Now:yyyy_MM_dd_HH_mm_ss}";

            if (saveFileDialog.ShowDialog() == true)
            {
                string path = saveFileDialog.FileName;
                string extension = System.IO.Path.GetExtension(path);

                _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);

                Task.Run(() =>
                {

                    XCode.Expression expression = CreateTimeRangeExpression();


                    var displayItemsValue = GetDisplayItem(MachineInfoValue);
                    //var entityDatas = QuiryEntity(null,expression);

                     if (extension.Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
                    {
                        if (ExportHelper.Export_ProductionData_xlsx(path, MachineInfoValue, expression, displayItemsValue))
                        {
                            "导出完成".MessageDialogs(MessageLevelType.成功, false, PopUpTypes.Global);
                        }
                        else
                        {
                            "导出失败".MessageDialogs(MessageLevelType.错误, false, PopUpTypes.Global);
                        }
                    }
                    else
                    {
                        "不支持的文件格式".MessageDialogs(MessageLevelType.错误, false, PopUpTypes.Global);
                    }
                   
                });
            }
        });



        
        public DelegateCommand<ProductionData> MouseDoubleClick => new DelegateCommand<ProductionData>(sender =>
        {
            if (sender != null) { return; }

        });

        public DelegateCommand<ListView> SelectUpdata => new DelegateCommand<ListView>(async sender =>
        {
            if (sender.SelectedItems.Count == 0)
            {
                return;
            }
            _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);

            await Task.Run(() =>
            {
                
            });
        });
        public DelegateCommand<ListView> SelectInputAndOutputUpdata => new DelegateCommand<ListView>(async sender =>
        {
            if (sender.SelectedItems.Count == 0)
            {
                return;
            }
            _ = DialogHost.Show(new LoadingDialogs(), PopUpTypes.Global.ToString()).ConfigureAwait(false);

            await Task.Run(() =>
            {
                

            });
        });

        private void Quiry()
        {
            _ = Task.Run(() =>
            {
                try
                {
                    PageParameter page = new PageParameter() { PageSize = PageCount, PageIndex = SeveralPage };
                    if (TotalPage == 1 || TotalPage == 0)
                    {
                        page.RetrieveTotalCount = true;
                    }
                    else
                    {
                        page.TotalCount = QuiryTotal;
                    }
                    //ViewUpdate();
                  
                    XCode.Expression expression = CreateTimeRangeExpression();
                
                    if (IsOutput)
                        expression &= ProductionData._.ResultOutput != 1;

                    IList<object> list=QuiryEntity(page, expression);
                    foreach (var item in list)
                    {
                        WeightList.Add(item);
                    }
                    //if ((TotalPage == 1 || TotalPage == 0) && string.IsNullOrEmpty(Barcode))
                    //{
                    //    TotalPage = (int)page.PageCount;
                    //}

                    TotalPage = (int)page.PageCount;
                    DisplayDataCount = list.Count();
                    QuiryTotal = (int)page.TotalCount;

                }
                catch (Exception ex)
                {
                    $"历史数据查询异常：{ex}".RunLog(MessageLevelType.警告);
                    if (ex.InnerException != null)
                    {
                        $"历史数据查询异常内部异常：{ex.InnerException.ToString()}".RunLog(MessageLevelType.警告);
                    }

                }
            }).ContinueWith(x =>
            {
                ThreadHelper.CrossThread(sender =>
                {
                    if (DialogHost.IsDialogOpen(PopUpTypes.Global.ToString()))
                    {
                        DialogHost.Close(PopUpTypes.Global.ToString());
                    }
                }, string.Empty);
            }).ConfigureAwait(false);
        }

        private IList<object> QuiryEntity(PageParameter page, XCode.Expression expression)
        {
            
            IList<object> list = null;
            switch (MachineInfoValue)
            {
                case MachineInfoTypes.卷芯上料:
                    list = CoilCoreLoadingData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.换套杯:
                    list = CupSleeveChangingData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.折极耳:
                    list = PoleEarFoldingData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.入壳机:
                    list = ShellInsertionData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.点底焊:
                    list = SpotoWeldData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.辊槽机:
                    list = GrooveRollingMachineData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.短路测试仪:
                    list = ShortCircuitTesterData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.左装盘机:
                    list = TrayFillerLeftData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.右装盘机:
                    list = TrayFillerRightData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.面垫机:
                    list = FaceCushionData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.左拆盘机:
                    list = DismantlingDiscLeftData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.右拆盘机:
                    list = DismantlingDiscRightData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.盖帽焊:
                    list = CapWeldingData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.封口机:
                    list = SealingMachineData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.清洗机:
                    list = CleaningData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.套膜机:
                    list = MantleData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.喷码机:
                    list = MarkingData.FindAll(expression, page).Cast<object>().ToList();
                    break;
                case MachineInfoTypes.预充装盘:
                    list = Plate.FindAll(expression, page).Cast<object>().ToList();
                    break;
                default: break;
            }
            return list;
        }
        public void Load()
        {
            //if (!_displayItems.IsDataUpdate)
            //{
            //    return;
            //}

            if (_configStatic.SCM.MainDeviceType == MainDeviceTypeEnum.前段组装线)
            {
                MachineInfoList = new List<object>
                {
                    MachineInfoTypes.卷芯上料,
                    MachineInfoTypes.换套杯,
                    MachineInfoTypes.折极耳,
                    MachineInfoTypes.入壳机,
                    MachineInfoTypes.面垫机,
                    MachineInfoTypes.点底焊,
                    MachineInfoTypes.辊槽机,
                    MachineInfoTypes.短路测试仪,
                };
                MachineInfoValue = MachineInfoTypes.卷芯上料;
            }
            else if (_configStatic.SCM.MainDeviceType == MainDeviceTypeEnum.前段装盘机)
            {
                MachineInfoList = new List<object>
                {
                    MachineInfoTypes.左装盘机,
                    MachineInfoTypes.右装盘机,
                };
                MachineInfoValue = MachineInfoTypes.左装盘机;
            }
            else if (_configStatic.SCM.MainDeviceType == MainDeviceTypeEnum.中段组装线)
            {
                MachineInfoList = new List<object>
                {
                    MachineInfoTypes.左拆盘机,
                    MachineInfoTypes.右拆盘机,
                    MachineInfoTypes.盖帽焊,
                    MachineInfoTypes.封口机,
                };
                MachineInfoValue = MachineInfoTypes.左拆盘机;
            }
            else if (_configStatic.SCM.MainDeviceType == MainDeviceTypeEnum.后段组装线)
            {
                MachineInfoList = new List<object>
                {
                    MachineInfoTypes.预充装盘,
                    MachineInfoTypes.喷码机,
                    MachineInfoTypes.套膜机,
                    MachineInfoTypes.清洗机,
                };
                MachineInfoValue = MachineInfoTypes.预充装盘;
            }


        }
        private void ViewUpdate(MachineInfoTypes value)
        {

          WeightList.Clear();
          DisplayDataCount = 0;
          TotalPage = 0;
            IsBarcodeDisplay = false;
            switch (value)
            {
                case MachineInfoTypes.卷芯上料:
                    IsBarcodeDisplay = true;
                    UpdateProductionDataViewColumns(_displayItems.CoilCoreLoadingDataDisplayItems);
                    break;
                case MachineInfoTypes.换套杯:
                    UpdateProductionDataViewColumns(_displayItems.CupSleeveChangingDataDisplayItems);
                    break;
                case MachineInfoTypes.折极耳:
                    UpdateProductionDataViewColumns(_displayItems.PoleEarFoldingDataDisplayItems);
                    break;
                case MachineInfoTypes.入壳机:
                    UpdateProductionDataViewColumns(_displayItems.ShellInsertionDataDisplayItems);
                    break;
                case MachineInfoTypes.点底焊:
                    UpdateProductionDataViewColumns(_displayItems.SpotoWeldDataDisplayItems);
                    break;
                case MachineInfoTypes.辊槽机:
                    UpdateProductionDataViewColumns(_displayItems.GrooveRollingMachineDataDisplayItems);
                    break;
                case MachineInfoTypes.短路测试仪:
                    UpdateProductionDataViewColumns(_displayItems.ShortCircuitTesterDataDisplayItems);
                    break;
                case MachineInfoTypes.左装盘机:
                    IsBarcodeDisplay = true;
                    UpdateProductionDataViewColumns(_displayItems.TrayFillerLeftDataDisplayItems);
                    break;
                case MachineInfoTypes.右装盘机:
                    IsBarcodeDisplay = true;
                    UpdateProductionDataViewColumns(_displayItems.TrayFillerRightDataDisplayItems);
                    break;
                case MachineInfoTypes.面垫机:
                    UpdateProductionDataViewColumns(_displayItems.FaceCushionDataDisplayItems);
                    break;
                case MachineInfoTypes.左拆盘机:
                    IsBarcodeDisplay = true;
                    UpdateProductionDataViewColumns(_displayItems.DismantlingDiscLeftDataDisplayItems);
                    break;
                case MachineInfoTypes.右拆盘机:
                    IsBarcodeDisplay = true;
                    UpdateProductionDataViewColumns(_displayItems.DismantlingDiscRightDataDisplayItems);
                    break;
                case MachineInfoTypes.盖帽焊:
                    UpdateProductionDataViewColumns(_displayItems.CapWeldingDataDisplayItems);
                    break;
                case MachineInfoTypes.封口机:
                    UpdateProductionDataViewColumns(_displayItems.SealingMachineDataDisplayItems);
                    break;
                case MachineInfoTypes.清洗机:
                    UpdateProductionDataViewColumns(_displayItems.CleaningDataDisplayItems);
                    break;
                case MachineInfoTypes.套膜机:
                    UpdateProductionDataViewColumns(_displayItems.MantleDataDisplayItems);
                    break;
                case MachineInfoTypes.喷码机:
                    UpdateProductionDataViewColumns(_displayItems.MarkingDataDisplayItems);
                    break;
                case MachineInfoTypes.预充装盘:
                    IsBarcodeDisplay=true;
                    UpdateProductionDataViewColumns(_displayItems.PlateDataDisplayItems);
                    break;
                default: break;
            }
        }

        private ObservableCollection<DisplayItemsModel> GetDisplayItem(MachineInfoTypes value)
        {
            var result = new ObservableCollection<DisplayItemsModel>();
            switch (value)
            {
                case MachineInfoTypes.卷芯上料:
                    result = _displayItems.CoilCoreLoadingDataDisplayItems;
                    break;
                case MachineInfoTypes.换套杯:
                    result = _displayItems.CupSleeveChangingDataDisplayItems;
                    break;
                case MachineInfoTypes.折极耳:
                    result = _displayItems.PoleEarFoldingDataDisplayItems;
                    break;
                case MachineInfoTypes.入壳机:
                    result = _displayItems.ShellInsertionDataDisplayItems;
                    break;
                case MachineInfoTypes.点底焊:
                    result = _displayItems.SpotoWeldDataDisplayItems;
                    break;
                case MachineInfoTypes.辊槽机:
                    result = _displayItems.GrooveRollingMachineDataDisplayItems;
                    break;
                case MachineInfoTypes.短路测试仪:
                    result = _displayItems.ShortCircuitTesterDataDisplayItems;
                    break;
                case MachineInfoTypes.左装盘机:
                    result = _displayItems.TrayFillerLeftDataDisplayItems;
                    break;
                case MachineInfoTypes.右装盘机:
                    result = _displayItems.TrayFillerRightDataDisplayItems;
                    break;
                case MachineInfoTypes.面垫机:
                    result = _displayItems.FaceCushionDataDisplayItems;
                    break;
                case MachineInfoTypes.左拆盘机:
                    result = _displayItems.DismantlingDiscLeftDataDisplayItems;
                    break;
                case MachineInfoTypes.右拆盘机:
                    result = _displayItems.DismantlingDiscRightDataDisplayItems;
                    break;
                case MachineInfoTypes.盖帽焊:
                    result = _displayItems.CapWeldingDataDisplayItems;
                    break;
                case MachineInfoTypes.封口机:
                    result = _displayItems.SealingMachineDataDisplayItems;
                    break;
                case MachineInfoTypes.清洗机:
                    result = _displayItems.CleaningDataDisplayItems;
                    break;
                case MachineInfoTypes.套膜机:
                    result = _displayItems.MantleDataDisplayItems;
                    break;
                case MachineInfoTypes.喷码机:
                    result = _displayItems.MarkingDataDisplayItems;
                    break;
                case MachineInfoTypes.预充装盘:
                    result = _displayItems.PlateDataDisplayItems;
                    break;
                default: break;
            }
            return result;
        }
        private void UpdateProductionDataViewColumns(ObservableCollection<DisplayItemsModel> Items)
        {

            //if (!_displayItems.IsHomeUpdate)
            //{
            //    return;
            //}
            try
            {
               ProductionDataView = new GridView();
                //ProductionDataView.Columns.Clear();

                List<DisplayItemsModel> list = new List<DisplayItemsModel>(Items);
                list.Sort((x, y) => x.CompareTo(y));

                foreach (var item in list)
                {
                    if (item.IsDisplay)
                    {
                        GridViewColumn gvc = new GridViewColumn { Header = item.Description };

                        if (item.DataType == "结果")
                        {
                            FrameworkElementFactory border = new FrameworkElementFactory(typeof(Border));
                            border.SetValue(Border.CornerRadiusProperty, new CornerRadius(3));
                            border.SetBinding(Border.BackgroundProperty, new Binding
                            {
                                Path = new System.Windows.PropertyPath(item.Name),
                                Converter = new Tools.Converter.ResultToColorConverter()
                            });

                            FrameworkElementFactory text = new FrameworkElementFactory(typeof(TextBlock));
                            text.SetValue(TextBlock.MarginProperty, new Thickness(5, 3, 5, 3));
                            text.SetValue(TextBlock.ForegroundProperty, new SolidColorBrush(Colors.White));
                            text.SetValue(TextBlock.HorizontalAlignmentProperty, System.Windows.HorizontalAlignment.Center);
                            text.SetBinding(TextBlock.TextProperty, new Binding { Path = new System.Windows.PropertyPath(item.Name) });

                            border.AppendChild(text);
                            var dataTemplate = new DataTemplate();
                            dataTemplate.VisualTree = border;
                            gvc.CellTemplate = dataTemplate;
                        }
                        else if (item.DataType == "浮点型")
                        {
                            gvc.DisplayMemberBinding = new Binding
                            {
                                Path = new System.Windows.PropertyPath(item.Name),
                                StringFormat = "F2"
                            };
                        }
                        else if (item.DataType == "时间型")
                        {
                            gvc.DisplayMemberBinding = new Binding
                            {
                                Path = new System.Windows.PropertyPath(item.Name),
                                StringFormat = "yyyy-MM-dd HH:mm:ss",
                                Converter = new Tools.Converter.TimeStampToDateTimeStringConverter()
                            };
                        }
                        else if (item.DataType == "扫码位置")
                        {
                            gvc.DisplayMemberBinding = new Binding
                            {
                                Path = new System.Windows.PropertyPath(item.Name),
                                Converter = new Tools.Converter.ScanPositionTypeConverter()
                            };
                        }
                        else if (item.DataType == "设备状态")
                        {
                            gvc.DisplayMemberBinding = new Binding
                            {
                                Path = new System.Windows.PropertyPath(item.Name),
                                Converter = new Tools.Converter.MachineStatusConverter()
                            };
                        }
                        else
                        {
                            item.Name = item.Name.Replace("_", "");
                            gvc.DisplayMemberBinding = new Binding { Path = new System.Windows.PropertyPath( item.Name) };
                        }
                        //Application.Current.Dispatcher.Invoke(() =>
                        //{
                           
                        //});
                        ProductionDataView.Columns.Add(gvc);

                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("6");
            }
        
        }


        public void UnLoad()
        {
        }

        //public XCode.Expression CreateTimeRangeExpression()
        //{
        //    ProductionData.Meta.TableName = $"ProductionData_{StartTime:yyyy}{StartTime.GetQuarterly()}";
        //    string[] stime = StartValidatingTime.Split(':');
        //    string[] etime = EndValidatingTime.Split(':');
        //    long startTime = SnowflakeManager.GetTimeId(new DateTime(StartTime.Year, StartTime.Month, StartTime.Day, int.Parse(stime[0]), int.Parse(stime[1]), int.Parse(stime[2]), 0, DateTimeKind.Local));
        //    long endTime = SnowflakeManager.GetTimeId(new DateTime(EndTime.Year, EndTime.Month, EndTime.Day, int.Parse(etime[0]), int.Parse(etime[1]), int.Parse(etime[2]), 999, DateTimeKind.Local));
        //    XCode.Expression expression = ProductionData._.SnowflakeId >= startTime & ProductionData._.SnowflakeId <= endTime;

        //    expression &= GenerateExpression(ResultTotalValue, ProductionData._.ResultTotal);
        //    expression &= GenerateExpression(ResultScanCodeBeforeValue, ProductionData._.ResultScanCodeBefore);
        //    expression &= GenerateExpression(ResultShortCicuteValue, ProductionData._.ResultShortCicute);
        //    expression &= GenerateExpression(ResultFormerWeighingValue, ProductionData._.ResultFormerWeighing);
        //    expression &= GenerateExpression(ResultAfterWeighingValue, ProductionData._.ResultAfterWeighing);
        //    expression &= GenerateExpression(ResultRefillWeighingValue, ProductionData._.ResultRefillWeighing);
        //    expression &= GenerateExpression(LeakResultValue, ProductionData._.LeakResult);

        //    return expression;
        //}

        //private XCode.Expression GenerateExpression(string value, XCode.Configuration.Field target)
        //{
        //    if (value != "全部")
        //    {
        //        ResultTypes enumValue;
        //        if (Enum.TryParse(value, out enumValue))
        //        {
        //            return target == enumValue;
        //        }
        //    }
        //    return null;
        //}
        public XCode.Expression CreateTimeRangeExpression()
        {
            var entityType = GetEntityType();
            //var entity = CreateEntityType<object>();
            string tableName = $"{entityType.Item1.Name}_{DateTime.Now:yyyy}{DateTime.Now.GetQuarterly()}";

            // 设置数据库表名
            PropertyInfo tableNameProperty = entityType.Item2.GetProperty("TableName", BindingFlags.Static | BindingFlags.Public);
            tableNameProperty.SetValue(entityType.Item3, Convert.ChangeType(tableName, tableNameProperty.PropertyType), null);


            ProductionData.Meta.TableName = $"ProductionData_{StartTime:yyyy}{StartTime.GetQuarterly()}";
            string[] stime = StartValidatingTime.Split(':');
            string[] etime = EndValidatingTime.Split(':');
            long startTime = SnowflakeManager.GetTimeId(new DateTime(StartTime.Year, StartTime.Month, StartTime.Day, int.Parse(stime[0]), int.Parse(stime[1]), int.Parse(stime[2]), 0, DateTimeKind.Local));
            long endTime = SnowflakeManager.GetTimeId(new DateTime(EndTime.Year, EndTime.Month, EndTime.Day, int.Parse(etime[0]), int.Parse(etime[1]), int.Parse(etime[2]), 999, DateTimeKind.Local));
           
            XCode.Expression expression = SpotoWeldData._.Id >= startTime & SpotoWeldData._.Id <= endTime;

            #region 添加筛选条件
            Action<string, XCode.Configuration.Field> processResultType = (resultValue, propertySelector) =>
            {
                if (resultValue != "全部" )
                {
                    XCode.Expression _expression = propertySelector == resultValue;
                    expression &= (_expression);
                }
            };


            if (IsBarcodeDisplay&&!string.IsNullOrWhiteSpace(Barcode))
            {
                switch(MachineInfoValue)
                {
                    case MachineInfoTypes.卷芯上料:
                        processResultType(Barcode, CoilCoreLoadingData._.PalletNo);
                        break;
                    case MachineInfoTypes.左装盘机:
                        processResultType(Barcode, TrayFillerLeftData._.PalletNo);
                        break;
                    case MachineInfoTypes.右装盘机:
                        processResultType(Barcode, TrayFillerRightData._.PalletNo);
                        break;
                    case MachineInfoTypes.左拆盘机:
                        processResultType(Barcode, DismantlingDiscLeftData._.PalletNo);
                        break;
                    case MachineInfoTypes.右拆盘机:
                        processResultType(Barcode, DismantlingDiscRightData._.PalletNo);
                        break;
                    case MachineInfoTypes.预充装盘:
                        processResultType(Barcode, Plate._.TrayBarcode);
                        break;
                    default:break;
                }
            }
        

            //// 使用委托处理不同的 ResultTypes 属性
            //processResultType(ResultTotalValue, ProductionData._.ResultTotal);
            //processResultType(ResultScanCodeBeforeValue, ProductionData._.ResultScanCodeBefore);
            //processResultType(ResultShortCicuteValue, ProductionData._.ResultShortCicute);
            //processResultType(ResultFormerWeighingValue, ProductionData._.ResultFormerWeighing);
            //processResultType(ResultAfterWeighingValue, ProductionData._.ResultAfterWeighing);
            //processResultType(ResultRefillWeighingValue, ProductionData._.ResultRefillWeighing);
            //processResultType(LeakResultValue, ProductionData._.LeakResult);
            //processResultType(AfterSealingResultValue, ProductionData._.AfterSealingResult);

            #endregion

            return expression;
        }

        public (Type, Type,object) GetEntityType()
        {
            Type resultType = null;
            Type resultMetaType = null;
            object entity = null;
            //MachineInfoTypes machineInfoType = (MachineInfoTypes)Enum.Parse(typeof(MachineInfoTypes), );
            switch (MachineInfoValue)
            {
                case MachineInfoTypes.卷芯上料:
                    resultType = typeof(CoilCoreLoadingData);
                    resultMetaType = typeof(CoilCoreLoadingData.Meta);
                    entity=new CoilCoreLoadingData();
                    break;
                case MachineInfoTypes.换套杯:
                    resultType = typeof(CupSleeveChangingData);
                    resultMetaType = typeof(CupSleeveChangingData.Meta);
                    entity = new CupSleeveChangingData();
                    break;
                case MachineInfoTypes.折极耳:
                    resultType = typeof(PoleEarFoldingData);
                    resultMetaType = typeof(PoleEarFoldingData.Meta);
                    entity = new PoleEarFoldingData();
                    break;
                case MachineInfoTypes.入壳机:
                    resultType = typeof(ShellInsertionData);
                    resultMetaType = typeof(ShellInsertionData.Meta);
                    entity = new ShellInsertionData();
                    break;
                case MachineInfoTypes.点底焊:
                    resultType = typeof(SpotoWeldData);
                    resultMetaType = typeof(SpotoWeldData.Meta);
                    entity = new SpotoWeldData();
                    break;
                case MachineInfoTypes.辊槽机:
                    resultType = typeof(GrooveRollingMachineData);
                    resultMetaType = typeof(GrooveRollingMachineData.Meta);
                    entity = new GrooveRollingMachineData();
                    break;
                case MachineInfoTypes.短路测试仪:
                    resultType = typeof(ShortCircuitTesterData);
                    resultMetaType = typeof(ShortCircuitTesterData.Meta);
                    entity = new ShortCircuitTesterData();
                    break;
                case MachineInfoTypes.左装盘机:
                    resultType = typeof(TrayFillerLeftData);
                    resultMetaType = typeof(TrayFillerLeftData.Meta);
                    entity = new TrayFillerLeftData();
                    break;
                case MachineInfoTypes.右装盘机:
                    resultType = typeof(TrayFillerRightData);
                    resultMetaType = typeof(TrayFillerRightData.Meta);
                    entity = new TrayFillerRightData();
                    break;
                case MachineInfoTypes.面垫机:
                    resultType = typeof(FaceCushionData);
                    resultMetaType = typeof(FaceCushionData.Meta);
                    entity = new FaceCushionData();
                    break;
                case MachineInfoTypes.左拆盘机:
                    resultType = typeof(DismantlingDiscLeftData);
                    resultMetaType = typeof(DismantlingDiscLeftData.Meta);
                    entity = new DismantlingDiscLeftData();
                    break;
                case MachineInfoTypes.右拆盘机:
                    resultType = typeof(DismantlingDiscRightData);
                    resultMetaType = typeof(DismantlingDiscRightData.Meta);
                    entity = new DismantlingDiscRightData();
                    break;
                case MachineInfoTypes.盖帽焊:
                    resultType = typeof(CapWeldingData);
                    resultMetaType = typeof(CapWeldingData.Meta);
                    entity = new CapWeldingData();
                    break;
                case MachineInfoTypes.封口机:
                    resultType = typeof(SealingMachineData);
                    resultMetaType = typeof(SealingMachineData.Meta);
                    entity = new SealingMachineData();
                    break;
                case MachineInfoTypes.清洗机:
                    resultType = typeof(CleaningData);
                    resultMetaType = typeof(CleaningData.Meta);
                    entity = new CleaningData();
                    break;
                case MachineInfoTypes.套膜机:
                    resultType = typeof(MantleData);
                    resultMetaType = typeof(MantleData.Meta);
                    entity = new MantleData();
                    break;
                case MachineInfoTypes.喷码机:
                    resultType = typeof(MarkingData);
                    resultMetaType = typeof(MarkingData.Meta);
                    entity = new MarkingData();
                    break;
                case MachineInfoTypes.预充装盘:
                    resultType = typeof(Plate);
                    resultMetaType = typeof(Plate.Meta);
                    entity = new Plate();
                    break;


                default:
                    return (resultType, resultMetaType, entity);
            }


            return (resultType, resultMetaType, entity);
        }
        void Test1()
        {

            Application.Current.Dispatcher.Invoke(() =>
            {

               
            });

        }
    }

    public class Test : ServierBase
    {
        public Test(DeviceConfigStatic deviceConfig, SystemConfigStatic systemConfig, UserConfigStatic userConfig, ParameterStatic parameterStatic, TemporaryStatic temporaryStatic, HomeStatic homeStatic) :
            base(deviceConfig, systemConfig, userConfig, parameterStatic, temporaryStatic, homeStatic)
        {
        }
    }
}
